﻿Imports System.Text.RegularExpressions
Public Class Form1

    ' // we must find the killer quickly. no time for comments or error checking!

    Private WithEvents proc As Process
    Dim rnd As New Random
    Dim running As Boolean = False
    Dim allow_sigterm As Boolean = True
    Dim killers_IP_address As String = Nothing
    Dim track_start_pos As Integer = 0

    Const INTRO_TEXT As String = "For weeks now we've been tracking the murders with a morbid fascination..."
    Const REALTIME_TEXT As String = "This isn't real-time..."
    Const TRACK_TEXT As String = "I'll create a GUI interface using visual basic, see if I can track an IP address"
    Const DONE_TEXT As String = "YEEEEAAAAAAAHHHHHHH"

    Const LOADING_TEXT As String = "Initializing HighMem for node 0 |" & _
        "Memory: 4859k kernel code, 25804k reserved, 2251k data, 660k init |" & _
        " |" & _
        "virtual kernel memory layout: |" & _
        " fixmap : 0xfff1d000 - 0xfffff000 ( 904 kB) |" & _
        " pkmap : 0xff800000 - 0xffc00000 (4096 kB) |" & _
        " vmalloc : 0xe5ff0000 - 0xff7fe000 ( 408 MB) |" & _
        " |" & _
        "Hierarchical RCU implementation. |" & _
        "NR_IRQS:2304 nr_irqs:256 |" & _
        "console [tty0] enabled |" & _
        "Detected 2075.289 MHz processor. |" & _
        " |" & _
        "Security Framework initialized |" & _
        "AppArmor: AppArmor initialized |" & _
        "Mount-cache hash table entries: 512 |" & _
        "Initializing cgroup subsys ns |" & _
        " |" & _
        "Ready and Waiting to Track The Killer's IP Address ..."

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If Not allow_sigterm Then
            txtTrackingOutput.AppendText("***** SYSTEM SHUTDOWN ENCOUNTERED, ABORTING SIGTERM KILL SIGNAL -- TRY AGAIN AFTER TRACK COMPLETES *****" & vbCrLf)
            e.Cancel = True
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.Text += String.Format(" - v{0}.{1}", My.Application.Info.Version.Major, My.Application.Info.Version.Minor)
        MoreTool.DropDown = ctmMoreOptions

        My.Forms.data_analyzer.Owner = Me
        My.Forms.data_analyzer.Top = Me.Top + 16
        My.Forms.data_analyzer.Left = Me.Left + Me.Width + 16
        My.Forms.data_analyzer.set_shot(1)
        My.Forms.data_analyzer.set_info_text(INTRO_TEXT)
        My.Forms.data_analyzer.Show()
        Me.Show()

        load_the_operating_system()


    End Sub


    Private Sub btnTrackNow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTrackNow.Click

        allow_sigterm = False
        btnTrackNow.Enabled = False
        txtTrackingOutput.SelectionLength = 0

        ' we have to show data being analyzed!
        My.Forms.data_analyzer.set_shot(4)
        My.Forms.data_analyzer.set_info_text(REALTIME_TEXT)
        sleep(4)

        My.Forms.data_analyzer.set_shot(2)
        My.Forms.data_analyzer.set_info_text(TRACK_TEXT)
        sleep(8)

        My.Forms.data_analyzer.start_analyzing()
        sleep(3)

        track_the_ip_address()

    End Sub

    Sub track_the_ip_address()

        Try

            track_start_pos = txtTrackingOutput.Text.Length
            killers_IP_address = Nothing
            tmr_check_proc_running.Start()

            txtTrackingOutput.AppendText("======================================" & vbCrLf)
            txtTrackingOutput.AppendText("<< Starting Tracking Initialization >>" & vbCrLf)
            sleep(2)

            Dim si As New ProcessStartInfo
            si.CreateNoWindow = True
            si.RedirectStandardOutput = True
            si.UseShellExecute = False
            si.FileName = cboActions.Text
            si.Arguments = txtKillersIP.Text

            proc = New Process
            proc.StartInfo = si
            proc.Start()

            running = True

            proc.SynchronizingObject = txtTrackingOutput
            proc.BeginOutputReadLine()

        Catch ex As Exception
            allow_sigterm = True
            btnTrackNow.Enabled = True
            proc = Nothing
            My.Forms.data_analyzer.stop_analyzing()
            txtTrackingOutput.AppendText(String.Format("[Error 404 ({1}): {2}]{0}", vbCrLf, cboActions.Text, ex.Message))
        End Try
    End Sub

    Sub load_the_operating_system()

        Dim loaders() As String = LOADING_TEXT.Split("|"c)

        For Each loadstring As String In loaders
            txtTrackingOutput.Text += loadstring & vbCrLf
            Application.DoEvents()
            Threading.Thread.Sleep(CInt(rnd.Next(3) * 123.5))
        Next

        btnTrackNow.Enabled = True

    End Sub

    Private Sub sleep(ByVal quarter_seconds As Integer)
        For id As Integer = 1 To (quarter_seconds * 2)
            Application.DoEvents()
            Threading.Thread.Sleep(125)
        Next
    End Sub

    Function get_last_ip_address() As String
        ' find the last ip address in the output via regex
        Dim barex As New Regex("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")
        Dim fooex As MatchCollection
        fooex = barex.Matches(txtTrackingOutput.Text, track_start_pos)
        If (fooex.Count = 0) Then
            Return Nothing
        Else
            Return fooex.Item(fooex.Count - 1).Value
        End If
    End Function

    Private Sub proc_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles proc.OutputDataReceived

        txtTrackingOutput.AppendText(e.Data & vbCrLf)

    End Sub

    Private Sub tmr_check_proc_running_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmr_check_proc_running.Tick
        If Not IsNothing(proc) Then
            If running And proc.HasExited Then

                tmr_check_proc_running.Stop()
                running = False

                sleep(2)
                txtTrackingOutput.AppendText("Closing your Ports...")
                sleep(1)
                txtTrackingOutput.AppendText(" [OK]" & vbCrLf)

                My.Forms.data_analyzer.stop_analyzing()

                sleep(2)
                txtTrackingOutput.AppendText("Shutting down console tty0...")
                sleep(1)
                txtTrackingOutput.AppendText(" [OK]" & vbCrLf)

                sleep(2)
                txtTrackingOutput.AppendText("Security Framework de-initializing...")
                sleep(1)
                txtTrackingOutput.AppendText(" [OK]" & vbCrLf)

                sleep(4)

                killers_IP_address = get_last_ip_address()

                txtTrackingOutput.AppendText(vbCrLf)
                txtTrackingOutput.AppendText(String.Format(">> Tracking Complete, Killer {0}! <<{1}", IIf(IsNothing(killers_IP_address), "NOT Found", String.Format("Found at IP {0}", killers_IP_address)), vbCrLf))

                My.Forms.data_analyzer.set_shot(3)
                My.Forms.data_analyzer.set_info_text(DONE_TEXT)
                btnTrackNow.Enabled = True

                txtKillersIP.SelectAll()

                If IsNothing(killers_IP_address) Then
                    lblKillersLost.Text = String.Format("Killers Lost: {0}", CInt(lblKillersLost.Tag) + 1)
                Else
                    lblKillersFound.Text = String.Format("Killers Found: {0}", CInt(lblKillersFound.Tag) + 1)
                End If

                allow_sigterm = True

            End If
        End If
    End Sub

    Private Sub cmiLicense_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmiLicense.Click
        Try
            Process.Start("http://guivbip.codeplex.com/license")
        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub cmiWebsite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmiWebsite.Click
        Try
            Process.Start("http://guivbip.codeplex.com/")
        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub
End Class
